package com.example.iitematicviewer.util.fileDownLoad;

import com.alibaba.fastjson.JSONObject;
import com.example.iitematicviewer.constant.Constant;
import com.example.iitematicviewer.constant.ExceptionConstant;
import com.example.iitematicviewer.vo.ResultVO;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

@Service
public class FileDownLoadService {

    public void down(HttpServletRequest request,HttpServletResponse response,ResultVO resultVO){
        // 请求类型、请求参数、请求头 根据需求制定即可
        // 获取到需要下载的文件
        // 如何生成文件，根据实际业务需求改造即可
        String outputFilePath = "D:\\file\\231536387250.jpg";
        // 下载文件
        // 设置响应的内容类型，让浏览器知道下载的是一个文件
        ServletContext context = request.getServletContext();
        // get MIME type of the file
        String mimeType = context.getMimeType(outputFilePath);
        if (mimeType == null) {
            // set to binary type if MIME mapping not found
            mimeType = "application/octet-stream";
        }
        // 设置响应头信息，告诉浏览器文件的名称和长度
        // set content attributes for the response
        response.setContentType(mimeType);
        // 设置编码
        response.setCharacterEncoding("utf-8");
        // Copy the stream to the response's output stream.
        try {
            InputStream myStream = new FileInputStream(outputFilePath);
            IOUtils.copy(myStream, response.getOutputStream());
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
